package com.qf.controller;

import com.qf.util.UploadUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

/*
杨威
2021/9/17
10:36
*/
@WebServlet("/upload")
@MultipartConfig
public class UploadController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String name = req.getParameter("name");
        Part file = req.getPart("file");
        //获取文件真实名称
        String fileName = file.getSubmittedFileName();
        //获取文件的UUID名称
        String newFileName = UploadUtil.getNewFileName(fileName);
        //获取文件上传的真实路径
        String loadPath=req.getServletContext().getRealPath("/WEB-INF/upload");
        //创建上传所在的文件
        File file1=new File(loadPath);
        //文件夹不存在就创建
        if(!file1.exists()){
            file1.mkdirs();
        }
        //根据真实路径和原文件名称的哈希码值创造出散列出处目录路径
        String newFilePath = UploadUtil.creatNewFilePath(loadPath, fileName);

        file.write(newFilePath+File.separator+newFileName);
        file.delete();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
